import axios from "axios";

const REQ = axios.create({
    headers: {
        "Content-Type": "application/json"
    },
    baseURL: "/api"
})

REQ.interceptors.request.use((instance) => {
    return instance
}, (config) => {
    console.error(config)
    window.messageApi.error("服务器错误，请联系网站管理员，稍后重试").then()
})

REQ.interceptors.response.use((instance) => {
    if (instance.data.status) {
        return instance.data
    } else {
        console.error(instance)
        window.messageApi.error(instance.data.msg).then()
        return Promise.reject()
    }
}, (error) => {
    if (error.response && error.response.status === 401) {
        if (error.response.data != null) {
            return error.response.data
        }
        return Promise.resolve({
            status: false,
            msg: "用户未登录",
            data: null
        })
    }
    console.error(error)
    if (error.response.data != null) {
        window.messageApi.error(error.response.data.msg).then()
    } else {
        window.messageApi.error("服务器错误，请联系网站管理员，稍后重试").then()
    }
    return Promise.reject()
})

export default REQ